/*******************************************************************************
 * Copyright (c) 2011 Irineu Martins de Lima Moura (imlm2).
 * This file is part of JBeat.
 * 
 *     JBeat is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     JBeat is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with JBeat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Irineu Martins de Lima Moura (imlm2) - initial API and implementation
 ******************************************************************************/
package br.ufpe.cin.imlm2.jbeat.soot.throwableset.generation;

import static br.ufpe.cin.imlm2.jbeat.soot.common.CommonExceptions.getARITHMETIC;
import static br.ufpe.cin.imlm2.jbeat.soot.common.CommonExceptions.getARRAYINDEXOUTOFBOUNDS;
import static br.ufpe.cin.imlm2.jbeat.soot.common.CommonExceptions.getARRAYSTORE;
import static br.ufpe.cin.imlm2.jbeat.soot.common.CommonExceptions.getCLASSCAST;
import static br.ufpe.cin.imlm2.jbeat.soot.common.CommonExceptions.getNEGATIVEARRAYSIZE;
import static br.ufpe.cin.imlm2.jbeat.soot.common.CommonExceptions.getNULLPOINTER;

import java.util.HashSet;
import java.util.Set;

import soot.Body;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.ThrowStmt;
import soot.jimple.toolkits.annotation.arraycheck.ArrayBoundsChecker;
import soot.jimple.toolkits.annotation.nullcheck.NullPointerChecker;
import soot.jimple.toolkits.annotation.tags.ArrayCheckTag;
import soot.jimple.toolkits.annotation.tags.NullCheckTag;
import soot.tagkit.Host;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.ThrowableSet;
import soot.util.Chain;
import br.ufpe.cin.imlm2.jbeat.soot.throwableset.ThrowableSetTagger;
import br.ufpe.cin.imlm2.jbeat.soot.throwableset.tags.ThrowableSetTag;
import br.ufpe.cin.imlm2.jbeat.soot.traps.TrapManager;

public class GeneratesCalculator extends ThrowableSetTagger {

	@Override
	protected void executePreTaggingTransformations() {
		super.executePreTaggingTransformations();
		for ( Host h : this.getTargetSet() ) {
			SootMethod sootMethod = (SootMethod) h;
			Body b = sootMethod.retrieveActiveBody();
			this.removeTags( b );
			ArrayBoundsChecker abc = ArrayBoundsChecker.v();
			abc.transform( b );
			NullPointerChecker npc = NullPointerChecker.v();
			npc.transform( b );
		}

	}

	@Override
	protected void executePostTaggingTransformations() {
		super.executePostTaggingTransformations();
		for ( Host h : this.getTargetSet() ) {
			SootMethod sootMethod = (SootMethod) h;
			Body b = sootMethod.retrieveActiveBody();
			this.removeTags( b );
		}
	}

	@Override
	protected void tag() {
		super.tag();
		for ( Host h : this.getTargetSet() ) {
			SootMethod meth = (SootMethod) h;
			Set<SootClass> exceptions = this.visitInstructions( meth );
			ThrowableSetTag tst = (ThrowableSetTag) meth.getTag( ThrowableSetTag.TAG_NAME );
			tst.addAllGeneratedExceptions( this.filterExceptions( exceptions, meth ) );
		}
	}

	private void removeTags( Body b ) {
		for ( Unit u : b.getUnits() ) {
			if ( u.hasTag( "NullCheckTag" ) )
				u.removeTag( "NullCheckTag" );
			if ( u.hasTag( "ArrayCheckTag" ) )
				u.removeTag( "ArrayCheckTag" );
		}
	}

	protected Set<SootClass> visitInstructions( SootMethod sootMethod ) {
		Body b = sootMethod.retrieveActiveBody();
		Chain<Unit> stmts = b.getUnits();
		Set<SootClass> generated = new HashSet<SootClass>();
		for ( Unit unit : stmts ) {
			generated.addAll( this.getGeneratedEscapedExceptions( unit, b ) );
		}
		return generated;
	}

	private Set<SootClass> getGeneratedEscapedExceptions( Unit u, Body b ) {
		Set<SootClass> generated = new HashSet<SootClass>();
		ThrowAnalysis ta = SimpleStmtThrowAnalysis.getInstance();
		ThrowableSet set;
		if ( u instanceof ThrowStmt )
			set = ta.mightThrowImplicitly( (ThrowStmt) u );
		else
			set = ta.mightThrow( u );
		SootClass[] commonExceptipns = { getARITHMETIC(), getARRAYINDEXOUTOFBOUNDS(),
				getARRAYSTORE(), getCLASSCAST(), getNEGATIVEARRAYSIZE(), getNULLPOINTER() };
		for ( SootClass sc : commonExceptipns ) {
			if ( set.catchableAs( sc.getType() ) ) {
				if ( !TrapManager.isExceptionCaughtAt( sc, u, b ) ) {
					generated.add( sc );
				}
			}
		}

		if ( u.hasTag( "NullCheckTag" ) ) {
			NullCheckTag nct = (NullCheckTag) u.getTag( "NullCheckTag" );
			if ( !nct.needCheck() )
				generated.remove( getNULLPOINTER() );
		}

		if ( u.hasTag( "ArrayCheckTag" ) ) {
			ArrayCheckTag act = (ArrayCheckTag) u.getTag( "ArrayCheckTag" );
			if ( !act.isCheckLower() && !act.isCheckUpper() )
				generated.remove( getARRAYINDEXOUTOFBOUNDS() );
		}
		return generated;
	}

}
